
const host = 'http://192.168.10.43:8804/';
import store from "../store/index.js";
const imgUrl = "http://8.134.15.11:8085/";
// 请求数据方法封装

const ajax = (opt) => {
	let token = ""
	try {
	   let userInfo = uni.getStorageSync('userInfo');
	   if(userInfo){
		   token = userInfo.token
	   }
	} catch (e) {
	    
	}
    opt = opt || {};
    opt.url = opt.url || '';
    opt.data = opt.data || null;
    opt.method = opt.method || 'POST';
    opt.header = opt.header || {
        "Content-Type": "application/json",
		"token":token
    };
	
	
    opt.success = opt.success || function () {};
	uni.showLoading({
		title: '正在加载中...',
		mask: true
	});
    uni.request({
        url: host + opt.url,
        data: opt.data,
        method: opt.method,
        header: opt.header,
        dataType: 'json',
        success: function (res) {
			uni.hideLoading();
			let code = res.data.code;
			let msg = res.data.msg;
			if (code >= 0) {// 接口正常请求
				
			} else {
				
				if(code < 0 && code >-1000){
					uni.showToast({
						title: '当前系统繁忙',
						duration: 1500,
						icon:'none',
						mask: true
					});
				} else if(code <=-2000 && code >= -2006){
					if(code>=-2006 && code<=-2001){
						store.commit("user/setUserInfo",null)
						uni.removeStorage({
						    key: 'userInfo',
						});
						uni.showToast({
							icon:"none",
							title:"请先登录",
							duration:1500
						})
						let has = location.hash
						let path = has.substring(1,has.length)
						path = '/pages/login/login?path=' + path
						let rt = setTimeout(()=>{
							uni.navigateTo({
								url:path
							})
						},1500)
						
					}
				}else{
					uni.showToast({
						title: msg,
						duration: 1500,
						icon:'none',
						mask: true
					});
				}
				
			} 
			opt.success(res.data);
        },
        fail: function () {
			uni.hideLoading();
            uni.showToast({
                title: '当前网络异常',
				icon:'none'
            });
        }
    })
}
// 文件上传封装
const uploadFile = opt => {
	opt.url = opt.url || '';
    opt.filePath = opt.filePath || null;//要上传文件资源的路径。   
	opt.name = opt.name || 'file';//文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容 
    opt.success = opt.success || function() {};
	uni.showLoading({
		mask:true
	})
	return new Promise((reslove,reject)=>{
		uni.uploadFile({
		    url: imgUrl + opt.url,
		    filePath:opt.filePath,
		    name:opt.name,
			fileType:opt.fileType,
		    success:function(res){
				uni.hideLoading()
				reslove(res)
		    },
		    fail: function (err) {
				reject(err)
				uni.hideLoading()
		        uni.showToast({
		            title: '请稍后重试'
		        });
		    }
		
		})
	})
	
}

export {
    ajax,
	uploadFile
}